#include "app_pool.h"
#include <mqueue.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>

static char *mq_name = "/mq_pool"; // 消息队列名字
static mqd_t mqd;                  // 消息队列的文件描述符
static pthread_t *threads;         // 线程池容器
static int thread_num;             // 线程池中线程数量

// 线程函数，不断循环接收任务并执行。如果没有任务，则阻塞等待。
static void *thread_func(void *arg)
{
    Task task;
    while (1)
    {
        ssize_t len = mq_receive(mqd, (char *)&task, sizeof(task), NULL);
        if (len == sizeof(Task))
        {
            task.func(task.arg);
        }
    }
}

int app_pool_init(int num)
{
    //创建多个线程，并保存到线程池容器中
    thread_num = num;
    threads = malloc(sizeof(pthread_t) * num);
    for (int i = 0; i < num; i++)
    {
        pthread_create(&threads[i], NULL, thread_func, NULL);
    }
    

    // 创建消息队列
    struct mq_attr attr;
    attr.mq_maxmsg = 10; // 消息队列中最多存放的消息数量
    attr.mq_msgsize = sizeof(Task);
    if ((mqd = mq_open(mq_name, O_CREAT | O_RDWR, 0644, &attr)) == -1)
    {
        perror("创建消息队列失败");
        return -1;
    }


    return 0;
}

int app_pool_close()
{
    for (int i = 0; i < thread_num; i++)
    {
        pthread_cancel(threads[i]);
        pthread_join(threads[i], NULL);
    }

    free(threads);

    mq_close(mqd);
    mq_unlink(mq_name);
    return 0;
}

int app_pool_registerTask(int (*func)(void *), void *argv)
{
    Task task =
        {
            .func = func,
            .arg = argv};
    return mq_send(mqd, (char *)&task, sizeof(task), 1);
}
